package com.ling.payservice.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.thread.ThreadUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ling.payservice.constant.AliPayConfig;
import com.ling.payservice.service.AliPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class AliPayServiceImpl implements AliPayService {

    @Override
    public Map<String, Object> ScanQRcode() throws AlipayApiException {

        AliPayConfig aliPayConfig = new AliPayConfig();

        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGateway_url(), aliPayConfig.getAppid(),
                aliPayConfig.getApp_private_key(), "json", "UTF-8", aliPayConfig.getAli_public_key(), "RSA2");
        AlipayTradePayRequest payRequest = new AlipayTradePayRequest();

        AlipayTradePrecreateModel precreateModel = new AlipayTradePrecreateModel();
        precreateModel.setTotalAmount("0.01");
        precreateModel.setSubject("啦啦啦，扫码支付呀");
        precreateModel.setBody("新增收入哦");
        precreateModel.setOutTradeNo("2012" + System.currentTimeMillis());

        payRequest.setBizModel(precreateModel);
        AlipayTradePayResponse payResponse = alipayClient.execute(payRequest);

        Map<String, Object> result = new HashMap<>();
        result.put("code", payResponse.getCode());
        result.put("msg", payResponse.getMsg());
        result.put("订单号", payResponse.getOutTradeNo());
        System.out.println("请求支付结果：" + payResponse.getCode());
        System.out.println("请求支付结果：" + payResponse.getMsg());
        System.out.println("请求支付结果：" + payResponse.getOutTradeNo());
        return result;
    }

    @Override
    public Map<String, Object> QRScan(String totalAmount, String authCode) throws AlipayApiException {
        log.info("付款码是：" + authCode);
        AliPayConfig aliPayConfig = new AliPayConfig();
        AlipayTradePayRequest payRequest = new AlipayTradePayRequest();
        AlipayTradePayModel payModel = new AlipayTradePayModel();
        payModel.setTotalAmount("10");
        payModel.setScene("bar_code");
        payModel.setSubject("汤圆的沙箱环境当面付");//支付宝APP——账单——账单详情——商品说明的内容
        payModel.setOutTradeNo(System.currentTimeMillis() + "");
        payModel.setTimeoutExpress("1m");
        payModel.setAuthCode(authCode);
        payRequest.setBizModel(payModel);
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGateway_url(), aliPayConfig.getAppid(), aliPayConfig.getApp_private_key(),
                "json", "UTF-8", aliPayConfig.getAli_public_key(), "RSA2");
        AlipayTradePayResponse payResponse = alipayClient.execute(payRequest);
        System.out.println("状态码：" + payResponse.getCode());
        System.out.println("信息提示：" + payResponse.getMsg());
        Map<String, Object> res = new HashMap<>(3);
        res.put("code", payResponse.getCode());
        res.put("msg", payResponse.getMsg());
        res.put("subMsg", payResponse.getSubMsg());
        //调用成功
        if (payResponse.isSuccess()) {
            if (payResponse.getCode().equals(aliPayConfig.ALI_QRCODE_PAY)) {
                //支付成功
                log.info("支付成功");
                return res;
            } else if (payResponse.getCode().equals(aliPayConfig.ALI_WAITCODE_PAY)) {
                //TODO 间隔3秒轮询请求alipay.trade.query查询交易状态，超过设置过期时间返回交易失败
                TimeInterval timer = DateUtil.timer();
                while (true) {
                    ThreadUtil.sleep(5000L);//未完成支付，间隔5秒发起请求查询支付状态
                    AlipayClient alipay = new DefaultAlipayClient(aliPayConfig.getGateway_url(),
                            aliPayConfig.getAppid(), aliPayConfig.getApp_private_key(), "json", "UTF-8", aliPayConfig.getAli_public_key(), "RSA2");  //获得初始化的AlipayClient
                    AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); //创建API对应的request类
                    AlipayTradePayModel tradePayModel = new AlipayTradePayModel();
                    tradePayModel.setOutTradeNo(payResponse.getTradeNo());
                    request.setBizModel(tradePayModel);//设置业务参数
                    AlipayTradeQueryResponse response = alipay.execute(request); //通过alipayClient调用API，获得对应的response类
                    System.out.print(response.getBody());
                    if (response.isSuccess()) {
                        //根据response中的结果继续业务逻辑处理
                        if (response.getCode().equals(aliPayConfig.ALI_QRCODE_PAY)) {
                            res.put("code", 0);
                            return res;
                        }
                        //超过一分钟，返回失败
                        if (timer.interval() >= 60 * 1000) {
                            res.put("code", -1);
                            res.put("msg","支付超时");
                            return res;
                        }
                    } else {
                        res.put("code", -1);
                        res.put("msg","获取订单状态失败");
                        return res;
                    }
                }
            }

            return res;

        }
        return res;
    }


}
